package com.szholly.pro.watergas_server.ps.android.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.springframework.util.Assert;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 表数据
 * 
 * 特性
 * 
 * 1.Key 都是大写的
 * 
 * 2.表名不能为空
 *
 * 
 * 2017/3/23 <br/>
 *
 * @author Joey Huang QQ:273179370）
 */
public class TableRowMap extends HashMap<String, Object> {
	private static final long serialVersionUID = 7097000926226250662L;
	private String mTableName;
	private FieldInterceptor[] interceptor;

	public TableRowMap(String tableName) {
		super();
		Assert.notNull(tableName, "表名为空");
		mTableName = tableName;
	}
	
	public void setFieldInterceptor(FieldInterceptor... interceptors){
		interceptor = interceptors;
	}
	
	public FieldInterceptor[] getFieldInterceptor(){
		return interceptor;
	}

	public String getTableName() {
		return mTableName;
	}

	@Override
	public Object put(String key, Object value) {
		Assert.notNull(key);
		return super.put(key.toUpperCase(), value);
	}

	@Override
	public Object get(Object key) {
		Assert.notNull(key);
		return super.get(key.toString().toUpperCase());
	}

	public String optString(String key) {
		return optString(key, null);
	}

	public String optString(String key, String def) {
		Assert.notNull(key);
		Object object = get(key);
		if (object == null) {
			return def;
		} else if (object instanceof String) {
			return (String) object;
		} else {
			return object.toString();
		}
	}

	public static TableRowMap get(JSONObject json, String tableName) {
		Assert.notNull(json);
		TableRowMap result = new TableRowMap(tableName);
		@SuppressWarnings("unchecked")
		Iterator<String> keys = json.keys();
		while (keys.hasNext()) {
			String key = keys.next();
			result.put(key, json.opt(key));
		}
		return result;
	}

	public static List<TableRowMap> get(JSONArray jsonArray, String tableName) {
		Assert.notNull(jsonArray);
		List<TableRowMap> result = new ArrayList<>();
		for (int i = 0; i < jsonArray.size(); i++) {
			result.add(get(jsonArray.optJSONObject(i), tableName));
		}
		return result;
	}
}
